import React, { useState, useEffect } from 'react';
import { Modal, Button, Steps, Typography, message } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';

const { Step } = Steps;

interface DisableAutoUpdateProps {
    open: boolean;
    onClose: () => void;
}

type StepStatus = 'wait' | 'process' | 'finish' | 'error';
interface StepState {
    title: string;
    status: StepStatus;
    description?: string;
}

const initialSteps: StepState[] = [
    { title: '关闭 Cursor 进程', status: 'wait' },
    { title: '删除更新器目录', status: 'wait' },
    { title: '修改 product.json', status: 'wait' },
    { title: '清空并锁定更新配置', status: 'wait' },
    { title: '创建更新阻止文件', status: 'wait' },
];

export const DisableAutoUpdate: React.FC<DisableAutoUpdateProps> = ({ open, onClose }) => {
    const [steps, setSteps] = useState<StepState[]>(initialSteps);
    const [isProcessing, setIsProcessing] = useState(false);
    const [current, setCurrent] = useState(0);

    useEffect(() => {
        // Reset state when modal is reopened
        if (open) {
            setSteps(initialSteps);
            setCurrent(0);
            setIsProcessing(false);
        }
    }, [open]);
    
    const updateStep = (index: number, status: StepStatus, description?: string) => {
        setSteps(prev => prev.map((step, i) => 
            i === index ? { ...step, status, description } : step
        ));
    };

    const runAllSteps = async () => {
        setIsProcessing(true);

        // Step Pre-check: Verify all paths are set
        try {
            const checkResult = await window.electronAPI.runTask<{ success: boolean; message?: string }>('update:check-paths');
            if (!checkResult.success) {
                message.error(checkResult.message || '执行失败，请先配置好所有必需的 Cursor 路径。');
                setIsProcessing(false);
                return;
            }
        } catch (e: unknown) {
            const error = e as Error;
            message.error(`路径检查失败: ${error.message}`);
            setIsProcessing(false);
            return;
        }

        // Step 0: Quit Cursor
        setCurrent(0);
        updateStep(0, 'process');
        try {
            const result = await window.electronAPI.runTask<{ message: string }>('quitCursor');
            updateStep(0, 'finish', result.message);
        } catch (e: unknown) {
            const error = e as Error;
            updateStep(0, 'error', error.message);
            setIsProcessing(false); return;
        }

        // Step 1: Remove Updater Directory
        setCurrent(1);
        updateStep(1, 'process');
        try {
            await window.electronAPI.runTask('update:removeDir');
            updateStep(1, 'finish', '更新器目录已删除。');
        } catch (e: unknown) {
            const error = e as Error;
            updateStep(1, 'error', error.message);
            setIsProcessing(false); return;
        }
        
        // Step 2: Modify product.json
        setCurrent(2);
        updateStep(2, 'process');
        try {
            await window.electronAPI.runTask('update:removeUrls');
            updateStep(2, 'finish', '成功移除更新链接。');
        } catch (e: unknown) {
            const error = e as Error;
            updateStep(2, 'error', error.message);
            setIsProcessing(false); return;
        }

        // Step 3: Clear and Lock update.yml
        setCurrent(3);
        updateStep(3, 'process');
        try {
            await window.electronAPI.runTask('update:lockYml');
            updateStep(3, 'finish', '更新配置文件 (update.yml) 已锁定。');
        } catch (e: unknown) {
            const error = e as Error;
            updateStep(3, 'error', error.message);
            setIsProcessing(false); return;
        }

        // Step 4: Create Blocking File for Updater
        setCurrent(4);
        updateStep(4, 'process');
        try {
            await window.electronAPI.runTask('update:createBlockingFile');
            updateStep(4, 'finish', '成功创建更新阻止文件。');
        } catch (e: unknown) {
            const error = e as Error;
            updateStep(4, 'error', error.message);
            setIsProcessing(false); return;
        }
        
        message.success("禁用自动更新流程已完成！");
        setIsProcessing(false);
    };

    const getStepIcon = (status: StepStatus) => {
        if (status === 'process') return <LoadingOutlined />;
        return undefined;
    };
    
    return (
        <Modal
            title="禁用 Cursor 自动更新"
            open={open}
            onCancel={onClose}
            width={600}
            footer={[
                <Button key="close" onClick={onClose} disabled={isProcessing}>
                    {isProcessing ? '处理中...' : '关闭'}
                </Button>,
                <Button key="start" type="primary" onClick={runAllSteps} loading={isProcessing}>
                    开始执行
                </Button>,
            ]}
        >
            <Typography.Paragraph type="secondary">
                此操作将修改 Cursor 的核心文件以阻止其自动更新。请确保您了解相关风险。建议在操作前备份重要数据。
            </Typography.Paragraph>
            <Steps direction="vertical" current={current} size="small">
                {steps.map((step, index) => (
                    <Step 
                        key={index} 
                        title={step.title}
                        status={step.status}
                        icon={getStepIcon(step.status)}
                        description={step.description && <Typography.Text type="secondary">{step.description}</Typography.Text>}
                    />
                ))}
            </Steps>
        </Modal>
    );
}; 